package com.xiaotao.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
//import com.second.hand.trading.server.service.OrderService;
import com.xiaotao.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class PayUtil {
    @Autowired
    private OrderService ordersService;
    //appid
    private final String APP_ID = "9021000157630907";
    //应用私钥
    private final String APP_PRIVATE_KEY ="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCZW1QghXAXwO6K1agp2c1o8mavpvzRyYtry7WtI35u0Qg8IBksXIB/7QvYRc35DzVjjSYKEcFdZDOqQe+Rx5jG8HgQVXN9Ya4/ApLKTPB0MtirPbZgVErfsRIrdMmNsnUvxuymRoHa5g6JGz6/EILfQNZdi7snpHPEDzdV1MC52IBNBlLUWGe37Wubdy7GjJZUiglgzbMRE3p0COMP5U8h6D7aa4CAncRehPb8DVhTArdoN3aW7h/DKrZFAFx6bxv5ZeAAxLqxcCBXSa0VjI8BIn8a9ZAEBmieFcoyL5U+PUu5YOnjsnz+g6HNO07zAEajpvjgWVHqD3R/VG9XvrhZAgMBAAECggEAJkJQpKRlqKdrW5ueDoLV6h6/W4cPf88GR2hU9NLsEf14Tne7kAOr0z5yPAx+LGqM6T8nhE+VrBT5hrpYaEghZ1BKw9htrZQXAoVD1dCIFJUy1NXakAG3hEMKw2ipd/5Tmg3IsFravp+ydKYla0lVPRlR4Zigom02rG0XYwRm6HYkLjqRgVgWDWMi+Zi61JBbiPHdKfvkAPBMRoqG5/ZGyTZKZ25I7ZTbuBBhne4/YVrRpW+igPfSlr4N6bBYpCqa6xBNCyJSGQwOuKF/mGZuKCmvhfjLHZa5IMKfUuX7Ko4l2GIjGVo29Uy+/NzcExB3QimE1jnymqIs/L65FWM5GQKBgQDv6ny8qC7YY9TkdosIxfoNHrOyaVSpb3S4XVkofYy7dk831FRRYbMz4uRtTw8jXTmRgKM75O7lRAJhFtSKrcWbZxjrMS8vU7KOHWvjEfJSsNs71DjMxFZZjwsUQd3RVMTFJJqRNgTXlggVdrWXHloZ+I6XA7RLNwP0J7ba7iuxtwKBgQCjo0j86xigv3TOuAN4r1Ke3CEWPbIgAjDa2Ht5BZEOrv6Geup98VMy3jSBj28LqW/KbfZ/I/J1fDw1HipHqTmw1UOncL2zxbwybDeo2mQ9ZnuwYhIEMKi4SwORzwrd/S29P7E3hhtedLs9BfOGarO6k/j9MC5ESXBHZa417vCmbwKBgC83dOkkKGQJ8cIs2lwVqoqeejsoo7Lc7pnCNWPUobfbJugT76w8kCosA0zH/HC3Tjcmm/mTqriQU++LsLTCUlutRKg0+9ZSoJd7jtoXlBtWFy+FKtCR63SgxEtuUxt5lWg/NfRSL03GhzzCKibdoFnwIw/xeLA82ZhZoJEhwpOtAoGAdAHlU5BjpEo2x/pCU8OPQhnyxu60IecLtYo1dqWQoaVDwhjPtrtn7S8EcDk8UzsqiosMbjQQxmNt14ZsGOOKh6eZT9IoWpM7CVAY4Xb6C2FlHLVZ6miIpCZiAHOUU64SSBEoVKGZM4xz1R4r98YbZpFSukP2+OhLVgJqz8d2CbcCgYBGIsstmiHtvWusVCv2WPefWutgyjVPnplLzJrUsBOwqGZODOxOKOdtRVGzTGFbfAsLIVR/I8u/yH1AHfjUYyS3hrhrd12pVDcPeKeq7hZeqEmSiP8fMj90lSQt4WvY3EVGBTrKfo1E8lFihbdKbTivw457TWLQZqdVcUaxGroK3A==";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhx3NKy1jDb3vnczITfd4g6O+iFb9v++0IIUVTeORdor0A2t2jkq8bGkc704x+0PRxonMb3o5ZC4mIMPemlIDfuBefKmwPjpKE/urE2xUeiMFNqknSH1MaYHx/TwcN7A5rdVQR+BbcbCHoObg4PdQpBwNXVUBTZ264G+jKVBdxNAa/8WICJZM0nzG4W6DCJQF8E6nKeQSEc7dpvI1RBpJdeTqXX9ExtJMsQArV8Y9LV0TNE720rL2/CWEZM48deTv763vosZUiUuFe9mslPJRKZy6GO6Ggbkuz1X7gQfUrpCfhb3BzuXq9qBjJtSgaYz3hUOJEGgNSt9g6JAaXi5TVwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://w65f6892.natappfree.cc/api/alipay/notify";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://w65f6892.natappfree.cc/api/alipay/return";
    private AlipayClient alipayClient = null;
    //支付宝官方提供的接口
    public String sendRequestToAlipay(String outTradeNo, BigDecimal totalAmount, String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body = "";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        JSONObject biz = new JSONObject();
        biz.put("out_trade_no", outTradeNo);
        biz.put("total_amount", totalAmount.toPlainString());
        biz.put("subject", subject);
        biz.put("body", "");
        biz.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(biz.toJSONString());


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        System.out.println("返回的结果是："+result );
        String payUrl =
                extractPayUrl(result);
        System.out.println(
                "提取出的支付链接："
                        + payUrl);
        return payUrl;

    }
    /**
     * 把支付宝返回的HTML form解析成一个可直接访问的支付链接
     */
    public String extractPayUrl(String htmlForm) {
        try {
            // 提取 action URL
            String action = htmlForm.split("action=\"")[1].split("\"")[0];

            // 匹配所有隐藏输入字段
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("<input type=\"hidden\" name=\"(.*?)\" value=\"(.*?)\">");
            java.util.regex.Matcher matcher = pattern.matcher(htmlForm);

            StringBuilder queryParams = new StringBuilder();
            while (matcher.find()) {
                if (queryParams.length() > 0) {
                    queryParams.append("&");
                }
                queryParams.append(matcher.group(1))
                        .append("=")
                        .append(java.net.URLEncoder.encode(matcher.group(2), "UTF-8"));
            }

            // 拼接完整URL
            return action + "?" + queryParams;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //    通过订单编号查询
    public String query(String id){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
    public String getAlipayPublicKey() {
        return ALIPAY_PUBLIC_KEY;
    }

}
